package com.xb.loan.util.binaryConvert.parse.map;


import com.xb.loan.util.binaryConvert.ConvertUtil;
import com.xb.loan.util.binaryConvert.config.ParseConfig;
import com.xb.loan.util.binaryConvert.config.ParseConfigManager;
import com.xb.loan.util.binaryConvert.exception.ParseException;
import com.xb.loan.util.binaryConvert.parse.ParseAble;
import com.xb.loan.util.binaryConvert.parse.ParsePointer;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


/**
 * //TODO 暂时只实现简单的map，即map的key和value不可能是map或者list
 * 
 * @author shiyin.chen
 * 
 */
@SuppressWarnings("unchecked")
public class MapParser implements ParseAble<Map> {

	@Override
	public Map convert(byte[] src, ParsePointer pointer, Class<?> clazz,
					   ParseConfig config) throws ParseException {
		
		int sizes = ConvertUtil.readSizes(src, pointer);
		
		if(sizes == 0){
			
			return null;
		}
		
		Map<Object, Object> map = new HashMap<Object, Object>(sizes);
		// 获取key类型
		Class<?> keyClazz = config.getKeyClass();
		// 获取解析key的parser
		ParseAble keyParser = ParseConfigManager.getParser(ParseConfigManager
				.getParseClassType(keyClazz));
		// 获取value类型
		Class<?> valueClazz = config.getValueClass();
		// 获取解析value的parser
		ParseAble valueParser = ParseConfigManager.getParser(ParseConfigManager
				.getParseClassType(valueClazz));
		
		for(int i=0;i<sizes;i++){
			
			Object key = keyParser.convert(src, pointer, keyClazz, null);
			
			Object value = valueParser.convert(src, pointer, valueClazz, null);
			
			map.put(key, value);
		}
		
		return map;
	}

	@Override
	public byte[] format(Map obj, ParseConfig config) throws ParseException {

		if (obj == null) {

			return new byte[] { 0 };
		}

		List<byte[]> elementBytes = new LinkedList<byte[]>();
		// 添加list属性长度
		byte[] sizeData = ConvertUtil.convertSizes(obj.size());

		elementBytes.add(sizeData);

		int sizes = sizeData.length;
		// TODO 只有一层
		// 获取key类型
		Class<?> keyClazz = config.getKeyClass();
		// 获取解析key的parser
		ParseAble keyParser = ParseConfigManager.getParser(ParseConfigManager
				.getParseClassType(keyClazz));
		// 获取value类型
		Class<?> valueClazz = config.getValueClass();
		// 获取解析value的parser
		ParseAble valueParser = ParseConfigManager.getParser(ParseConfigManager
				.getParseClassType(valueClazz));
		
		for (Object object : obj.entrySet()) {
			
			Entry entry = (Entry) object;
			// key的字节
			byte[] keyData = keyParser.format(entry.getKey(), null);
			
			sizes+= keyData.length;
			
			elementBytes.add(keyData);
			// value的字节
			byte[] valueData = valueParser.format(entry.getValue(), null);
			
			sizes+= valueData.length;
			
			elementBytes.add(valueData);
			
		}

		return ConvertUtil.combatAll(elementBytes, sizes);
	}

}
